package com.zlxtk.databaseExplain;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.word.Word07Writer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.*;
import java.util.List;

/**
 * 导出word文档
 */
public class WordServiceImpl {
    private File file;
    private Word07Writer writer;
    private static short rowHeight = 20;
    private static short cellWidth = 20;

    public WordServiceImpl() {
        try {
            // 创建excel文件
            File f = new File("");
            String dataFile = f.getCanonicalPath() + File.separator + "data.doc";
            file = new File(dataFile);
            writer = new Word07Writer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void WriteDateToWord(List<List<String>> tables, String tableName, String comment) throws Exception {

        //标题
        // writer.addText(new Font("宋体", Font.PLAIN, 18), comment);

        XWPFDocument doc = writer.getDoc();

        //创建标题样式
        XWPFStyles newStyles = doc.createStyles();
        String headStyle1 = "head_style_1";//样式名称
        createHeadingStyle(doc, newStyles, headStyle1, 2, 18, "000000", "宋体");

        //下入标题
        XWPFParagraph interfaceNamePara = doc.createParagraph(); //创建一个新段落
        interfaceNamePara.setStyle(headStyle1);//使用样式
        BigInteger numID = getNewDecimalNumberingId(doc, BigInteger.valueOf(0));//设置序号
        interfaceNamePara.setNumID(numID);//添加序号
        XWPFRun run = interfaceNamePara.createRun(); //一个XWPFRun代表具有相同属性的一个区域
        run.setText(comment + "(" + tableName + ")");
        // run.setColor("000000"); //设置字段颜色
        run.setBold(true); //设置字段是否粗体，true为粗体
        // run.setFontFamily("宋体");//字体
        run.setFontSize(12);


        //写入表格
        writer.addTable(tables);

        //加个空行
        writer.addText(new Font("宋体", Font.PLAIN, 12), "");

        // 写出到文件
        writer.flush(file);

    }

    /**
     * 获取输出流
     *
     * @return
     * @throws Exception
     */
    private FileOutputStream getOutputStream() throws Exception {
        FileOutputStream out = new FileOutputStream(file);
        return out;
    }

    public void close() {
        writer.close();
    }

    static BigInteger getNewDecimalNumberingId(XWPFDocument document, BigInteger abstractNumID) {
        CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
        cTAbstractNum.setAbstractNumId(abstractNumID);

        CTLvl cTLvl = cTAbstractNum.addNewLvl();
        cTLvl.setIlvl(BigInteger.valueOf(0)); // set indent level 0
        cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
        cTLvl.addNewLvlText().setVal("1.2.%1");
        cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

        XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);

        XWPFNumbering numbering = document.createNumbering();

        abstractNumID = numbering.addAbstractNum(abstractNum);

        BigInteger numID = numbering.addNum(abstractNumID);

        return numID;
    }

    /**
     * @param doc
     * @param styles
     * @param strStyleId   标题id
     * @param headingLevel 标题级别
     * @param pointSize    字体大小（/2）
     * @param hexColor     字体颜色
     * @param typefaceName 字体名称（默认宋体）
     */
    public void createHeadingStyle(XWPFDocument doc, XWPFStyles styles, String strStyleId,
                                   int headingLevel, int pointSize, String hexColor, String typefaceName) {
        //创建样式
        CTStyle ctStyle = CTStyle.Factory.newInstance();
        //设置id
        ctStyle.setStyleId(strStyleId);

        CTString styleName = CTString.Factory.newInstance();
        styleName.setVal(strStyleId);
        ctStyle.setName(styleName);

        CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
        indentNumber.setVal(BigInteger.valueOf(headingLevel));

        // 数字越低在格式栏中越突出
        ctStyle.setUiPriority(indentNumber);

        CTOnOff onoffnull = CTOnOff.Factory.newInstance();
        ctStyle.setUnhideWhenUsed(onoffnull);

        // 样式将显示在“格式”栏中
        ctStyle.setQFormat(onoffnull);

        // 样式定义给定级别的标题
        CTPPr ppr = CTPPr.Factory.newInstance();
        ppr.setOutlineLvl(indentNumber);
        ctStyle.setPPr(ppr);

        XWPFStyle style = new XWPFStyle(ctStyle);

        CTHpsMeasure size = CTHpsMeasure.Factory.newInstance();
        size.setVal(new BigInteger(String.valueOf(pointSize)));
        CTHpsMeasure size2 = CTHpsMeasure.Factory.newInstance();
        size2.setVal(new BigInteger(String.valueOf(pointSize)));

        CTFonts fonts = CTFonts.Factory.newInstance();
        if (typefaceName == null || typefaceName.equals("")) typefaceName = "宋体";
        fonts.setAscii(typefaceName);    //字体

        CTRPr rpr = CTRPr.Factory.newInstance();
        rpr.setRFonts(fonts);
        rpr.setSz(size);
        rpr.setSzCs(size2);    //字体大小

        CTColor color = CTColor.Factory.newInstance();
        color.setVal(hexToBytes(hexColor));
        rpr.setColor(color);    //字体颜色
        style.getCTStyle().setRPr(rpr);
        // is a null op if already defined

        style.setType(STStyleType.PARAGRAPH);
        styles.addStyle(style);
    }

    public static byte[] hexToBytes(String hexString) {
        HexBinaryAdapter adapter = new HexBinaryAdapter();
        byte[] bytes = adapter.unmarshal(hexString);
        return bytes;
    }


}
